import store from '../store'
import {
    createRoom,
    joinRoom,
    signalPeerData
} from './socket'
import Peer from 'simple-peer';
const defaultConstraints = { // 默认约束条件
    audio: true,
    video:true
    // video: {
    //     width: "480",
    //     height: "360"
    // } // 设置视频的分辨率，不设置默认最高画质
}

let localStream;
// 采集音视频并初始化连接
export const getPreviewAndInitConnection = (isRoomHost, meettingUserName, roomId) => {
    // 获取媒体访问权限 https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia
    navigator.mediaDevices.getUserMedia(defaultConstraints)
        .then(function (stream) {
            /* 使用这个stream stream */
            localStream = stream
            localStream.getAudioTracks()[0].enabled = false // 默认禁音
            // 预览视频
            previewVideo(localStream)
            // 初始化房间连接
            isRoomHost ? createRoom(meettingUserName) : joinRoom(roomId, meettingUserName);
        })
        .catch(function (err) {
            /* 处理error */
            console.log(err);
            // TODO 使用框架提示无法获取媒体流
        });
}


// 响应webRTC
let peers = {};
let streams = []
export const responseRTCConnection = (connectUserSocketId, isInitiator) => {
    const config = getConfig()
    //实例化对等连接对象
    peers[connectUserSocketId] = new Peer({
        initiator: isInitiator,
        config: config,
        stream: localStream
    })

    // 信令数据交换,监听signal事件，并将data传递给其他人，其中data是自身的一些数据信息
    // 说明文档：https://www.npmjs.com/package/simple-peer
    // (对应官网文档里peer2.signal(data))
    peers[connectUserSocketId].on('signal', data => {
        const signalData = {
            signal: data,
            connectUserSocketId
        }
        signalPeerData(signalData)
    })

    // 获取媒体流
    peers[connectUserSocketId].on('stream', stream => {
        // 显示接收的stream流
        addStream(stream, connectUserSocketId)
        streams = [...streams, stream]
    })
}


// 配置STUN服务器,克服NAT影响
const getConfig = () => {
    return {
        iceServers: [{
            urls: 'stun:stun1.l.google.com:19302',
        }, ],
    };
};

// 将信令数据添加到接收webRTC对等连接准备的一方的对等对象中,(对应官网文档里peer2.signal(data))
export const handleSignalingData = (data) => {
    peers[data.connectUserSocketId].signal(data.signal)
}

// 移除退出房间用户的信息
export const removePeerConnection = data => {
    const {
        socketId
    } = data;

    // 断开srcObject信息
    const video = document.getElementById(socketId)

    if (video) {
        const tracks = video.srcObject.getTracks();
        tracks.forEach(t => {
            t.stop()
        });

        video.srcObject = null
    }

    // 删除vuex中的数据
    store.commit('meeting/REMOVE_STREAMSOURCE', socketId)

    // 删除peer中的信息
    if (peers[socketId]) {
        peers[socketId].destroy()
    }

    delete peers[socketId];
}

// 预览视频
const previewVideo = (stream) => {
    store.commit('meeting/SET_STREAMSOURCE', {
        stream
    })
}

// 添加接收的stream媒体流并进行显示
const addStream = (stream, connectUserSocketId) => {
    store.commit('meeting/SET_STREAMSOURCE', {
        stream,
        connectUserSocketId
    })
}

// 是否静音操作,isMicOn:是否开启麦克风
export const toogleMic = isMicOn => {
    localStream.getAudioTracks()[0].enabled = isMicOn
}

// 是否关闭摄像头操作，isCameraOn：是否开启摄像头
export const toggleCamera = isCameraOn => {
    localStream.getVideoTracks()[0].enabled = isCameraOn
}

// 是否切换共享屏幕操作，isShareOn:是否开启共享屏幕，shareStream共享的数据流
export const toggleScreen = (isShareOn, shareStream = null) => {
    let stream = isShareOn ? shareStream : localStream

    for (let socketId in peers) {
        for (let index in peers[socketId].streams[0].getTracks()) {
            for (let sIndex in stream.getTracks()) {
                if (peers[socketId].streams[0].getTracks()[index].kind === stream.getTracks()[sIndex].kind) {
                    peers[socketId].replaceTrack(peers[socketId].streams[0].getTracks()[index], stream.getTracks()[sIndex], peers[socketId].streams[0])
                }
            }
        }
    }
}